import {
	Component
} from 'react';
import {
	Tab,
	Button,
	ScrollList,
	Group,
	Datetime,
	Boxs,
	Avatar,
	Badge,
	Popup,
	ActionSheet,
	Dialog,
	Toast,
	SearchBar
} from 'saltui';
const {
	IconButton,
	ButtonGroup,
} = Button;
const {
	HBox,
	Box,
	VBox
} = Boxs;

import PageController from 'pages/home';
import {
	urlPrefix,
	URLS,
	nodataIcon,
	dictMap
} from '../../../app/variables';
import DB from '../../../app/db';
import PostPageItem from 'components/post_page_item';
import './PageHome.less';
let tabPage = '0';
// let skipPostId = "";
// let pageCount = 1;
// let flag = false;
export default class PageHome extends Component {

	constructor(props) {
		super(props);
		let winHeight = getScrollHigh(1, 1, 0);
		var context = document.getElementById("context").value;
		this.state = {
			winHeight: parseInt(winHeight) - 2 + "px",
			activeTabIndex:tabPage,
			boardId: props.params.boardId ? props.params.boardId : '',
			replyCount:props.params.replyCount ? props.params.replyCount : '',
			postCount:props.params.postCount ? props.params.postCount : '',
			boardName:props.params.boardName ? props.params.boardName : '',
			attIdJson:props.params.attIdJson ?	props.params.attIdJson : '',
			visible:false,
			search: {
				title:'',
				startDate:'',
				endDate:''
			},
			typeArrow:true,
			addClickAble:false,
			noDataTip:"暂无数据",
			urlPrev: context + '/api/m/plugin/attachment/mobile/viewImage?fid=',
		}

		this.searchBarProps = {
			placeholder: "搜贴,找人",
			instantSearch: false,
			hasHistory: false,
			searchDelay: 450,
			exitAfterEnter: false,
			onEnter: () => {
			},
			onExit: this.onExit.bind(this),
			onChange: (value) => {
			},
			onSearch: this.onSearch.bind(this)
		};
	}
	componentDidMount() {
		this.flushData({}, tabPage);
		Dialog.hide();
		//获取首页信息,限制字数
		let t = this;
		t.searchBarLimit('30');
	}
    //限制字数
	searchBarLimit(len){
		$(".t-search-bar-input").attr('maxlength',len);
	}

	componentWillUnmount(){
		tabPage = '0';
	}

	handleTabChange(obj) {
		var t = this;
		var active = obj.active;
		tabPage = obj.active;
		this.setState({
			activeTabIndex: active,
			search: {title:''},
		});
		this.flushData({}, active);
		t.searchBarLimit('30');
	}

	/**
	 * 点击新增按钮跳转到新增页面
	 */
	addButtonClick() {
		location.href = '#/post/edit';
	}

	onExit() {
		this.onSearch1("");	
	}

	onSearch1(value) {
		let param = this.state.search;
		param.title=value;
		this.flushData(param,tabPage);
		this.setState({
			noDataTip:"暂无数据"
		});
	}


	onSearch(value) {
		this.setState({
			noDataTip:"无搜索结果"
		});
		let param = this.state.search;
		param.title=value;
		param.startDate=this.state.search.startDate;
		param.endDate=this.state.search.endDate;
    	this.flushData(param,tabPage);
	}

	changeArrow(field){
		let t = this;
		let status = t.state[field];
		t.setState({
			[field]:!status
		})
	}

	onRefresh(value) {
		let param = this.state.search;
		param.title=value;
		param.startDate=this.state.search.startDate;
		param.endDate=this.state.search.endDate;
    	this.flushData(param,tabPage);
	}

	flushNewData(param) {
		this.refs.post_new_ref.fetchData(param);
	}

	flushHotData(param) {
		this.refs.post_hot_ref.fetchData(param);
	}

	flushEssenceData(param) {
		this.refs.post_essence_ref.fetchData(param);
	}

	flushNoticeData(param) {
		this.refs.post_notice_ref.fetchData(param);
	}

	//日期选择器开关
	showSlot(id) {
		this[id].show();
	}

	//时间格式化   YYYY-MM-DD
	formatterDate(time){
		var date = new Date(time);
		var Y = date.getFullYear() + '-';
		var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
		var D = date.getDate() < 10 ? "0" + (date.getDate()) : date.getDate();
		return Y+M+D;
	}

	refresh(){
		let param = this.state.search;
		param.title=this.state.search.title;
		param.startDate=this.state.search.startDate;
		param.endDate=this.state.search.endDate;
    	this.flushData(param,tabPage);
	}


	flushData(param, index) {
		let swap_index = index ? index : this.state.activeTabIndex;
		if (swap_index == '0') {
			dd.biz.navigation.setTitle({
      		title: '最新',
		    onSuccess: function (result) {
		    },
     		onFail: function () {
      		}
    		});
			this.flushNewData(param);
		} else if (swap_index == '1') {
			dd.biz.navigation.setTitle({
      		title: '最热',
		    onSuccess: function (result) {
		    },
     		onFail: function () {
      		}
    		});
			this.flushHotData(param);
		}
		else if (swap_index == '2') {
			dd.biz.navigation.setTitle({
      		title: '精华',
		    onSuccess: function (result) {
		    },
     		onFail: function () {
      		}
    		});
			this.flushEssenceData(param);
		}
		else if (swap_index == '3') {
			dd.biz.navigation.setTitle({
      		title: '公告',
		    onSuccess: function (result) {
		    },
     		onFail: function () {
      		}
    		});
			this.flushNoticeData(param);
		}
	}

	beforeFetch(data, from) {
		this.setState({
			addClickAble:false,
		});
		data.activeTabIndex = this.state.activeTabIndex;
		data.rows = data.pageSize;
		data.limit = data.pageSize;
		data.title=this.state.search.title;
		data.boardId = this.state.boardId;
		if(this.state.search.startDate != null && this.state.search.startDate != ''){
			data.startDate = this.formatterDate(this.state.search.startDate);
		}
		if(this.state.search.endDate != null && this.state.search.endDate != ''){
			data.endDate = this.formatterDate(this.state.search.endDate);
		}
		data.type="1";//以公告置顶排序
		return data;
	}

	processData(data) {
		this.setState({
			addClickAble:true,
		});
		return data;
	}

	changeClickAble(){
		this.setState({
			addClickAble:true,
		});
	}

	//日期选择确认
	onOk(value,key){
		let t = this;
		if(key == "startDate" && t.state.search.endDate != null && t.state.search.endDate != ''){
			if(t.formatterDate(t.state.search.endDate) < t.formatterDate(value.value)){
			Toast.show({
				type: 'error',
				content: '开始日期不能大于结束日期'
			});
			return;
			}
		}
		if(key == "endDate" && t.state.search.startDate != null && t.state.search.startDate != ''){
			if(t.formatterDate(t.state.search.startDate) > t.formatterDate(value.value)){
			Toast.show({
				type: 'error',
				content: '结束日期不能小于开始日期'
			});
			return;
			}
		}
		if(key == "startDate"){
			var title = t.state.search.title;
			var endDate = t.state.search.endDate;
			t.setState({
				search :{
					title:title,
					startDate:t.formatterDate(value.value),
					endDate:endDate
				}
			});
		}else{
			var title = t.state.search.title;
			var startDate = t.state.search.startDate;
			t.setState({
				search :{
					title:title,
					startDate:startDate,
					endDate:t.formatterDate(value.value),
				}
			});
		}
	}

	render() {
		let winHeightStyle = {
			height: this.state.winHeight
		};
		const datetimeProps = {
			locale: 'zh-cn',
		};
		let token = document.getElementById("token").value;
		var url=this.state.urlPrev;
		let photo_html="";
		var imageContent ="";
		if(this.state.attIdJson!="" && this.state.attIdJson!=null){
			var s = "";
			imageContent = url+this.state.attIdJson+'&token='+token
		}
		photo_html = 
		( this.state.attIdJson=="" || this.state.attIdJson==null
		 ?
		 <i className="iconfont icon-forum t-FS24 t-LH44 t-FCf"></i>
		 :
		 <img className="dd-t-list-img t-P0 no-border" src={imageContent}/>)
		return (
			<div className="forums-index t-PB44 t-BCf">
				<HBox className="dd-top-border t-PL16 t-PR16 t-PT14" vAlign="center">
					<HBox flex={1}>
					<Box className="dd-t-list-img t-MR12 t-P0 no-border " style={{ background: 'rgba(56,172,255,.5)' }}>
						{photo_html}
					</Box>
					<Box className="dd-t-list-text-content" flex={1}>
						<p className="dd-t-list-title t-LH1_6 t-omit t-FC3 t-PT2">{this.state.boardName}</p>
						<div className="dd-t-list-time t-FBAC t-FBH t-PB10 t-PT4 ">
						<span className="t-FS14 t-FCddfontblue-60 t-MR16">主题 {this.state.postCount}</span>
						<span className="t-FS14 t-FCddfontblue-60 ">评论 {this.state.replyCount}</span>
						</div>
					</Box>
					</HBox>
				</HBox>
				 <Tab activeKey={this.state.activeTabIndex} onChange={this.handleTabChange.bind(this)} destroyInactiveTabPane={true}>
				 	<Tab.Item key="0" title={"最新"}>
					<VBox className="dd-bottom-border">
						<HBox className="t-BCf" vAlign="center">
							<Box flex={1}><SearchBar ref="search_forum_list_ref_new" {...this.searchBarProps} /></Box>
							<Box className="t-FCddblue" onClick={() => { 
								this.setState({ visible: true });
								var top = $(window).scrollTop();
								$('#App').css("top",-top+"px");
								$('#App').css("width",100+"%");
								$('#App').css('position','fixed');
								}}>
								<i className="iconfont icon-filter t-FS18 t-FCblue t-LH44 t-PR10"></i>
							</Box>
						</HBox>
					</VBox>
					<div style={winHeightStyle} >
						<ScrollList
						url={URLS.queryPostPageWithNew}
						dataType="json"
						pageSize={10}
						ref="post_new_ref"
						beforeFetch={this.beforeFetch.bind(this)}
						processData={this.processData.bind(this)}
						onRefresh={this.onRefresh.bind(this)}
						noDataImage={nodataIcon}
						noDataTip={this.state.noDataTip}
						currentPageKey="page"
						fetchDataOnOpen={false}
						>
						<PostPageItem pagetype="board"  addClickAble={this.state.addClickAble} changeClickAble={this.changeClickAble.bind(this)} isShowCount={true} isShowLabel={true} flushData={this.flushNewData.bind(this)} />
						</ScrollList>
					</div>
			        </Tab.Item>
					<Tab.Item key="1" title={"最热"}>
					<VBox className="dd-bottom-border">
						<HBox className="t-BCf" vAlign="center">
							<Box flex={1}><SearchBar ref="search_forum_list_ref_hot" {...this.searchBarProps} /></Box>
							<Box className="t-FCddblue" onClick={() => { 
								this.setState({ visible: true });
								var top = $(window).scrollTop();
								$('#App').css("top",-top+"px");
								$('#App').css("width",100+"%");
								$('#App').css('position','fixed');
								}}>
								<i className="iconfont icon-filter t-FS18 t-FCblue t-LH44 t-PR10"></i>
							</Box>
						</HBox>
					</VBox>
					<div style={winHeightStyle}>
						<ScrollList
						url={URLS.queryPostPageWithHot}
						dataType="json"
						pageSize={10}
						ref="post_hot_ref"
						beforeFetch={this.beforeFetch.bind(this)}
						processData={this.processData.bind(this)}
						onRefresh={this.onRefresh.bind(this)}
						noDataImage={nodataIcon}
						noDataTip={this.state.noDataTip}
						currentPageKey="page"
						fetchDataOnOpen={false}
						>
						<PostPageItem pagetype="board"  addClickAble={this.state.addClickAble} changeClickAble={this.changeClickAble.bind(this)} isShowCount={true} isShowLabel={true} activeValue={this.state.activeTabIndex} flushData={this.flushHotData.bind(this)} />
						</ScrollList>
					</div>
          			</Tab.Item>
          			<Tab.Item key="2" title={"精华"}>
					<VBox className="dd-bottom-border">
						<HBox className="t-BCf" vAlign="center">
							<Box flex={1}><SearchBar ref="search_forum_list_ref_essence" {...this.searchBarProps} /></Box>
							<Box className="t-FCddblue" onClick={() => { 
								this.setState({ visible: true });
								var top = $(window).scrollTop();
								$('#App').css("top",-top+"px");
								$('#App').css("width",100+"%");
								$('#App').css('position','fixed');
								}}>
								<i className="iconfont icon-filter t-FS18 t-FCblue t-LH44 t-PR10"></i>
							</Box>
						</HBox>
					</VBox>
					<div style={winHeightStyle}>
						<ScrollList
						url={URLS.queryPostPageWithHot}
						dataType="json"
						pageSize={10}
						ref="post_essence_ref"
						beforeFetch={this.beforeFetch.bind(this)}
						processData={this.processData.bind(this)}
						onRefresh={this.onRefresh.bind(this)}
						noDataImage={nodataIcon}
						noDataTip={this.state.noDataTip}
						currentPageKey="page"
						fetchDataOnOpen={false}
						>
						<PostPageItem pagetype="board"  addClickAble={this.state.addClickAble} changeClickAble={this.changeClickAble.bind(this)} isShowLabel={true} isShowCount={true} activeValue={this.state.activeTabIndex} flushData={this.flushEssenceData.bind(this)} />
						</ScrollList>
					</div>
          			</Tab.Item>
					<Tab.Item key="3" title={"公告"}>
					<VBox className="dd-bottom-border">
						<HBox className="t-BCf" vAlign="center">
							<Box flex={1}><SearchBar ref="search_forum_list_ref_notice" {...this.searchBarProps} /></Box>
							<Box className="t-FCddblue" onClick={() => { 
								this.setState({ visible: true });
								var top = $(window).scrollTop();
								$('#App').css("top",-top+"px");
								$('#App').css("width",100+"%");
								$('#App').css('position','fixed');
								}}>
								<i className="iconfont icon-filter t-FS18 t-FCblue t-LH44 t-PR10"></i>
							</Box>
						</HBox>
					</VBox>
					<div style={winHeightStyle}>
						<ScrollList
						url={URLS.queryPostPageWithHot}
						dataType="json"
						pageSize={10}
						ref="post_notice_ref"
						beforeFetch={this.beforeFetch.bind(this)}
						processData={this.processData.bind(this)}
						onRefresh={this.onRefresh.bind(this)}
						noDataImage={nodataIcon}
						noDataTip={this.state.noDataTip}
						currentPageKey="page"
						fetchDataOnOpen={false}
						>
						<PostPageItem pagetype="board"  addClickAble={this.state.addClickAble} changeClickAble={this.changeClickAble.bind(this)} isShowLabel={true} isShowCount={true} activeValue={this.state.activeTabIndex} flushData={this.flushNoticeData.bind(this)} />
						</ScrollList>
					</div>
          			</Tab.Item>
				 </Tab>
				 <Popup
					content={
						<div style={{height:'100vh'}}>
						<div className="dd-popup-mail-right" style={{width:"280px",paddingTop:0,height:"calc(100% - 80px)",overflowY:"auto"}}>
						    <HBox vAlign="center"
								className={!this.state.typeArrow?"t-P16 t-PT14 t-PB0 t-FS16 t-MT4":"dd-bottom-border t-P16 t-PT14 t-PB0 t-FS16 t-MT4"}
								onClick={this.changeArrow.bind(this,"typeArrow")}>
								<Box flex={1} className="t-FC3">发布日期</Box>
								<Box><i className={this.state.typeArrow?"iconfont icon-arrow-down t-FCddblue":"iconfont icon-arrow-up t-FCddblue"} ></i></Box>
							</HBox>
							<HBox vAlign="center" className={!this.state.typeArrow?"t-PL16":"t-DN"}>
								<Box className="t-FC9 t-FS14">开始日期</Box>
								<Box className="t-BCf7 t-LH32 t-R4 t-ML5" onClick={() => {this.showSlot('slot1');}} style={{width:'84%'}}>
									<p className="t-FAC t-H26">{this.state.search.startDate} <i className="iconfont icon-calendar t-FS14 t-FCblue t-FR t-MR10"></i></p>
									<Datetime
									{...datetimeProps}
									slotRef={s => this.slot1 = s}
									title="日期选择"
									placeholder="开始日期"
									value={this.state.search.startDate}
									columns={Datetime.YMD}
									onConfirm={(value) => {this.onOk(value, 'startDate'); }}
									onCancel={() => {  }}
									/>
								</Box>
							</HBox>
							<div className="t-H10"></div>
							<HBox vAlign="center" className={!this.state.typeArrow?"t-PL16":"t-DN"}>
                                <Box className="t-FC9 t-FS14">结束日期</Box>
                                <Box className="t-BCf7 t-LH32 t-R4 t-ML5" onClick={() => {this.showSlot('slot2');}} style={{width:'84%'}}>
                                <p className="t-FAC t-H26">{this.state.search.endDate}<i className="iconfont icon-calendar t-FS14  t-FCblue t-FR t-MR10"></i></p>
								<Datetime
								{...datetimeProps}
								slotRef={s => this.slot2 = s}
								title="日期选择"
								placeholder="结束日期"
								value={this.state.search.endDate}
								columns={Datetime.YMD}
								onConfirm={(value) => { this.onOk(value, 'endDate'); }}
								onCancel={() => {  }}
								/>
							</Box>
							</HBox>
							<div className="t-bottom-fixed"  style={{borderTop:0,bottom:'0',width:'100%'}}>
							<ButtonGroup onClick={() => { Popup.hide(); }}>
								<Button type="secondary" display="inline" onClick={() => { this.setState({search:{startDate:'',endDate:'',title:this.state.search.title},noDataTip:'暂无数据'}, ()=>{ this.refresh() }) }}>重置</Button>
								<Button type="primary" display="inline" onClick={() => {this.setState({visible: false,noDataTip:'无搜索结果'}); this.refresh() }}>确定</Button>
							</ButtonGroup>
							</div>
						</div>
						</div>
					}
					animationType="slide-left"
					onMaskClick={() => { this.setState({ visible : false }); }}
				    visible={this.state.visible}
					>
					{null}
				</Popup>
			</div>
		);
	}
}